import 'dart:core';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:mybaseplus/base/tool/empty/FFEmpty.dart';

///Platform.pathSeparator表示路径分隔符，对于Android和iOS来说表示‘/’
///recursive：false代表操作当前目录。true表示包含所有子目录

class FFDirectory {

  static String getPathSeparator(){
    return Platform.pathSeparator;
  }

  //判断文件类型
  static bool isDirectory(String directory) {
    FileSystemEntityType type = FileSystemEntity.typeSync(directory);
    return type == FileSystemEntityType.directory;
  }

  //判断目录是否存在
  static Future<bool> isExistDirectory(String directory) async {
    if (!isDirectory(directory)) return false;

    Directory dir = Directory(directory);
    return dir.exists();
  }

  static Future<bool> createDirectory(String directory) async {
    bool exist = await isExistDirectory(directory);
    if (exist) {
      return true;
    }

    try {
      Directory dir = Directory(directory);
      Directory? toDir = await dir.create(recursive: true);
      if (toDir == null) {
        return false;
      }
      return true;
    } catch (e) {
      debugPrint("createDirectory e = $e");
      return false;
    }
    return false;
  }

  //删除目录
  static Future<void> deleteDirectory(String directory,{bool? recursive = false}) async {
    bool exist = await isExistDirectory(directory);
    if (exist == true) {
      Directory dir = Directory(directory);
      try {
        await dir.delete(recursive: recursive??false);
      } catch (e) {
        debugPrint("deleteDirectory ${directory}");
      }
    }
  }

  //根据一个目录，查找当前目录下的文件
  static Future<List<File>?> findChildFileByDir(String dir) async {
    List<File> files = [];
    if (FFEmpty.stringIsEmpty(dir)) {
      return files;
    }

    if (FFDirectory.isDirectory(dir) != true) {
      return files;
    }

    bool exist = await FFDirectory.isExistDirectory(dir);
    if (exist == false) {
      return files;
    }

    Directory directory = Directory(dir);

    (await directory.list()).forEach((element) {

    });
    await directory.list().forEach((element) {
      if (element is File) {
        files.add(element);
      }
    });

    return files;
  }

  //根据一个目录，查找当前目录下的目录
  static Future<List<Directory>?> findChildDirByDir(String dir) async {
    List<Directory> dirs = [];
    if (FFEmpty.stringIsEmpty(dir)) {
      return dirs;
    }

    if (FFDirectory.isDirectory(dir) != true) {
      return dirs;
    }

    bool exist = await FFDirectory.isExistDirectory(dir);
    if (exist == false) {
      return dirs;
    }

    Directory directory = Directory(dir);

    await directory.list().forEach((element) {
      if (element is Directory) {
        dirs.add(element);
      }
    });

    return dirs;
  }
}
